import { _decorator, AudioSource, Component, director, Label, Node } from 'cc';
import { GameData } from '../commons/GameData';
import { GameState } from '../commons/GameConst';
import { GameEvent } from '../commons/GameEvent';
const { ccclass, property } = _decorator;

@ccclass('GameOverView')
export class GameOverView extends Component {

    @property(Label)
    curScoreLabel: Label = null!;

    @property(Label)
    bestScoreLabel: Label = null!;

    @property([Node])
    medalNodeList: Node[] = [];

    private _music: AudioSource = null;

    public onUpdateShowGameOverInfo(data?:any){
        let curScore = GameData.instance.curScore;
        if(this.curScoreLabel){
            this.curScoreLabel.string = `${curScore.toString()}`;
        }

        if(this.bestScoreLabel){
            this.bestScoreLabel.string = `${GameData.instance.bestScore}`;
        }

        let showMedalIndex = 0;
        for(let i = 0;i < this.medalNodeList.length;i++){

            const element = this.medalNodeList[i];

            if(!element){
                continue;
            }

            if(curScore >= 30){
                showMedalIndex = 2;
            }else if(curScore >= 20){
                showMedalIndex = 1;
            }else if(curScore >= 10){
                showMedalIndex = 0;
            }
        }

        if(curScore >= 10){
           for(let i = 0;i < this.medalNodeList.length;i++){
               if(i == showMedalIndex){
                   this.medalNodeList[i].active = true;
               }else{
                   this.medalNodeList[i].active = false;
               }
           }
        }

    }

    public show(){
        this.node.active = true;
        if(this._music){
            this._music.play();
        }else{
            this._music = this.node.getComponent(AudioSource);
            this._music.play();
        }
    }

    public hide(){
        this.node.active = false;
        if(this._music){
            this._music.stop();
        }
    }

    public onClickRestartBtn(){
        director.emit(GameEvent.GAME_EVENT_RESTART);
        GameData.instance.restGameData();

        this.hide();
    }

    protected onDestroy(): void {
        director.off(GameEvent.GAME_EVENT_RESTART);
    }

    start() {
        this._music = this.node.getComponent(AudioSource);
    }

    update(deltaTime: number) {
        
    }
}


